package com.pgcomb.poweriot.alarmservice.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

 /**
   * @description: 线程池配置
   * @author zhengheqi
   * @date 2021/5/29 14:53
   * @version 1.0.0
   */
@Configuration
@EnableAsync
@EnableScheduling
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        int numOfCPU = Runtime.getRuntime().availableProcessors();
        float rateOfCPU = 0.7f;
        int threadCount = (int) (numOfCPU * rateOfCPU + 1);

        // 队列最大长度 >=mainExecutor.maxSize 队列设为threadCount*3，目前改成设置定值
        poolTaskExecutor.setQueueCapacity(500);

        // 核心线程数 并行线程设为threadCount
        poolTaskExecutor.setCorePoolSize(threadCount * 2);

        // 最大线程数设为threadCount*5
        poolTaskExecutor.setMaxPoolSize(threadCount * 5);

        // 线程池维护线程所允许的空闲时间 1min
        poolTaskExecutor.setKeepAliveSeconds(60);

        // 初始化
        poolTaskExecutor.initialize();

        return poolTaskExecutor;
    }
}
